class SuppliersController < ApplicationController

  before_filter :authorize_show, :only => [ :index ]

  def index
      
  end

  def show
    @supplier = Supplier.find(params[:id])

    respond_to do |format|
      format.html
    end
  end

  def new
    @supplier = Supplier.new

    respond_to do |format|
      format.html
    end
  end

  def edit
    @supplier = Supplier.find(params[:id])
  end

  def create
    @supplier = Supplier.new(params[:supplier])

    respond_to do |format|
      if @supplier.save
        format.html { redirect_to(:back, :notice => 'Supplier was successfully created.') }
      else
        format.html { redirect_to(:back, :notice => 'be ima nekfi greshki') }
      end
    end
  end

  def update
    @supplier = Supplier.find(params[:id])

    respond_to do |format|
      if @supplier.update_attributes(params[:supplier])
        format.html { redirect_to(@supplier, :notice => 'Supplier was successfully updated.') }
      else
        format.html { render :action => "edit" }
      end
    end
  end

  def destroy
    @supplier = Supplier.find(params[:id])
    @supplier.destroy

    respond_to do |format|
      format.html { redirect_to(suppliers_url) }
      format.xml  { head :ok }
    end
  end
  
  def login
    
  end  
  
  def do_login
    user = Supplier.authenticate(params[:email], params[:password])
    if user
      session[:supplier_user_id] = user.id
      redirect_to suppliers_path
    else
      flash.now.alert = "Invalid email or password"
      render "login"
    end    
  end
  
  def filters
    @filters = Filter.all
  end  
  
  def add_filter
    @filter = Filter.new(params[:filter])
    @filter.save
    respond_to do |format|
      format.html { redirect_to(suppliers_filters_path) }
    end    
  end
  
  def destroy_filter
    @filter = Filter.find(params[:id])
    @filter.destroy

    respond_to do |format|
      format.html { redirect_to(suppliers_filters_path) }
    end    
  end
  
  def logout
    session[:supplier_user_id] = nil
    redirect_to suppliers_path
  end
  
  def update_car_brand_select
    car_models = CarModel.where(:car_brand_id => params[:id]).order(:name) unless params[:id].blank?
    render :partial => "car_models", :locals => { :car_model_id => nil, :car_models => car_models }        
  end
  
  private
    def authorize_show
      if current_supplier.nil?
        redirect_to suppliers_login_path
      end
    end
  
end
